//index.js
//获取应用实例
var api = require("../../utils/api.js");
var util = require("../../utils/util.js");
var click = require("../template/commodity/commodity.js");

const app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    btns: [{
        id: 1,
        img: "../../res/icon-module_01.png",
        title: "去签到",
      },
      {
        id: 2,
        img: "../../res/icon-module_02.png",
        title: "排行榜",
      },
      {
        id: 3,
        img: "../../res/icon-module_03.png",
        title: "邀好友",
      },
      {
        id: 4,
        img: "../../res/icon-module_04.png",
        title: "凑步数",
      },
    ],
    banners: [],
    commoditys: [],
    pageIndex: 1,
    pageNum: 1,
    talentCoin: -1,
    dayStep: -1,
    bubble: [],
    bubbleAnimation: null,
    bubbleAnimationNum: 0,
    bubbleIndex: null,
    animation: null,
    animationNum: 0,
    peopleAnimation: null,
    peopleAnimationNum: 0,
    coinAnimation: null,
    animationEndNum: 0,
    cardNum: -1,
    signMsg: null,
    signStep: 0,
    showSignView: false,
    showSignDialog: false,
    shareType: 0,
    shareInfo: null,
  },
  //加载数据
  loadData: function() {
    this.getBanners();
    this.getCommoditys(false);
  },
  //获取用户步数信息
  getUserStep: function() {
    //首次登陆
    api.checkUserFirstLogin(res => {
      if (res.is_first == 1 && res.sign == 2) {
        this.setData({
          showSignDialog: true
        });
      }
    });
    //获取微信运动信息
    wx.getWeRunData({
      success: res => {
        api.getUserStep(app.globalData.userStatus.uid, app.globalData.userStatus.session, res.iv, res.encryptedData, res => {
          app.globalData.userStep = res;
          //气泡显示
          var bubble = [];
          var sign = res.bubble.sign;
          var send = res.bubble.send;
          var step = res.bubble.step;

          if (step > 0) {
            bubble.push({
              type: 'step',
              number: step,
              name: '行走'
            });
          }
          if (sign > 0) {
            bubble.push({
              type: 'sign',
              number: sign,
              name: '签到'
            });
          }
          if (send > 0) {
            bubble.push({
              type: 'send',
              number: send,
              name: '赠送'
            });
          }

          this.setData({
            talentCoin: parseFloat(res.point),
            dayStep: res.step,
            bubble: bubble,
          });
          //分享跳转
          this.shareJump();
          //更新达人币
          this.updateCoin();
        });
      }
    });
  },

  //分享跳转
  shareJump: function() {
    if (this.data.shareType == 1) {
      var shareInfo = JSON.parse(this.data.shareInfo);
      if (shareInfo && app.globalData.userStatus.open_id != shareInfo.openid){
        util.toSponsor(this.data.shareInfo);
      }
    }

    this.setData({
      shareType: 0,
    })
  },
  //获取banner
  getBanners: function() {
    api.banners(1, banners => {
      this.setData({
        banners: banners,
      });
    });
  },
  //获取商品
  getCommoditys: function(load) {
    if (!load) {
      this.setData({
        pageIndex: 1,
      });
    }
    api.goods(0, this.data.pageIndex, 1, (goods, allIndex) => {
      this.setData({
        pageIndex: ++this.data.pageIndex,
        pageNum: allIndex,
        commoditys: load ? this.data.commoditys.concat(goods) : goods,
      });
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.loadData();
    this.bgAnimation();

    var type = options.type ? options.type : 0;
    if (type > 0) {
      this.setData({
        shareType: type,
        shareInfo: options.shareInfo ? options.shareInfo : '',
      })
    }
  },
  //背景动画开始
  bgAnimation: function() {
    this.startAnimation(100);
  },

  startAnimation: function(delay) {
    var animation = wx.createAnimation({
      timingFunctionL: 'linear',
    });
    this.setData({
      animation: animation.export(),
    });
    var timeout = setTimeout(function() {
      clearTimeout(timeout);
      animation.translate(0).step({
        duration: 1,
      }).translate(wx.getSystemInfoSync().windowWidth).step({
        duration: 10000,
      });
      this.setData({
        animation: animation.export(),
      })
    }.bind(this), delay);
  },
  //背景动画结束监听
  bgAnimationEnd: function(a) {
    this.setData({
      animationNum: ++this.data.animationNum,
    });
    if (this.data.animationNum % 2 == 0) {
      this.startAnimation(1);
    }
  },
  //点击功能按钮
  clickFunction: function(e) {
    // console.log(e.currentTarget.dataset.item);
    switch (e.currentTarget.dataset.item.id) {
      case 1:
        util.toSign();
        break;
      case 2:
        util.toRank();
        break;
      case 3:
        break;
      case 4:
        util.toPoster();
        break;
    }
  },

  //点击banner
  clickBanner: function(e) {
    var banner = e.currentTarget.dataset.banner;
    // type 1小程序 2h5
    api.bannerLog(banner.id);
    if (banner.type == 1) {
      util.toMiniProgram(banner.appid, banner.url);
    } else {
      util.toWeb(banner.name, banner.url);
    }
  },

  //点击商品
  clickCommodity: function(e) {
    click.commodity(e.currentTarget.dataset.commodity, e.currentTarget.dataset.type);
  },
  //点击气泡
  clickBubble: function(e) {
    this.setData({
      bubbleIndex: e.currentTarget.dataset.index,
    });
    this.startPeopleAnimation();
  },

  //人动画开始
  startPeopleAnimation: function(e) {
    if (this.data.bubble.length > 0 && this.data.bubbleIndex == null) {
      this.setData({
        bubbleIndex: 0,
      });
    } else if (this.data.bubble.length <= 0) {
      this.setData({
        bubbleIndex: null,
      })
    }
    var animation = wx.createAnimation({
      timingFunctionL: 'linear',
    });
    this.setData({
      peopleAnimation: animation.export(),
    });
    var timeout = setTimeout(function() {
      clearTimeout(timeout);
      animation.translate(0, -16).step({
        duration: 300,
      }).translate(0).step({
        duration: 300,
      });
      this.setData({
        peopleAnimation: animation.export(),
      })
    }.bind(this), 0);
  },
  //结束
  peopleAnimationEnd: function(e) {
    this.setData({
      peopleAnimationNum: ++this.data.peopleAnimationNum,
    });
    if (this.data.peopleAnimationNum % 2 == 0) {
      this.setData({
        peopleAnimation: null,
      });
      if (this.data.bubbleIndex != null) {
        this.startBubbleAnimation();
      }
    }
  },

  //气泡动画
  startBubbleAnimation: function() {
    var bubble = this.data.bubble[this.data.bubbleIndex];
    api.receiveBubble(bubble.type, res => {
      var coin = this.data.talentCoin + bubble.number;
      this.setData({
        animationEndNum: coin,
      });
      var animation = wx.createAnimation({
        timingFunctionL: 'linear',
      });
      this.setData({
        bubbleAnimation: animation.export(),
      });
      var timeout = setTimeout(function() {
        clearTimeout(timeout);
        animation.translate(0, -16).step({
          duration: 200,
        }).translate(-16, -32).opacity(0).step({
          duration: 300,
        }).translate(0).opacity(1).step({
          duration: 1,
        });
        this.setData({
          bubbleAnimation: animation.export(),
        })
      }.bind(this), 0);
    });
  },

  //气泡动画结束
  bubbleAnimationEnd: function(e) {
    this.setData({
      bubbleAnimationNum: ++this.data.bubbleAnimationNum,
    });
    if (this.data.bubbleAnimationNum % 3 == 0) {
      this.startCoinAnimation();
      var bubble = this.data.bubble;
      bubble.splice(this.data.bubbleIndex, 1);
      this.setData({
        bubbleIndex: null,
        bubbleAnimation: null,
        talentCoin: this.data.animationEndNum,
        bubble: bubble,
      });
      this.updateCoin();
      //校验
      // this.getUserStep();
    }
  },
  updateCoin: function() {
    //更新达人币总数
    app.globalData.userStatus.point = this.data.talentCoin;
  },
  //闪烁动画
  startCoinAnimation: function() {
    var animation = wx.createAnimation({
      timingFunctionL: 'linear',
      duration: 300,
    });
    this.setData({
      coinAnimation: animation.export(),
    });
    var timeout = setTimeout(function() {
      clearTimeout(timeout);
      animation.opacity(1).step().opacity(0).step().opacity(1).step().opacity(0).step();
      this.setData({
        coinAnimation: animation.export(),
      })
    }.bind(this), 0);
  },

  hideSignDialog: function(e) {
    this.setData({
      showSignDialog: false,
    });
  },

  //点击签到
  clickSign: function(e) {
    wx.showLoading({});
    api.sign(res => {
      wx.hideLoading();
      this.setData({
        signMsg: res.message,
        signStep: res.sign_step,
        cardNum: res.card_name,
      });
      this.setData({
        showSignView: true,
      });
      this.getData();
    }, () => {
      wx.hideLoading();
    });

  },
  //隐藏签到页面
  hideSignView: function(e) {
    this.setData({
      showSignView: false,
    });
  },

  intercept: function(e) {

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    if (app.globalData.userStatus) {
      this.getUserStep();
    } else {
      app.userStatusReadyCallback = res => {
        this.getUserStep();
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.loadData();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    if (this.data.pageIndex <= this.data.pageNum) {
      this.getCommoditys(true);
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return app.shareSeekHelp(util.sponsorPath(app.globalData.userStatus.open_id));
  }
})